#!/usr/bin/env python3
# -*- coding: UTF-8 -*-

import os
import argparse

# software_root="/home/plus/Downloads/bash-4.2"
# root_dir="base"

parser = argparse.ArgumentParser()
parser.add_argument(
    '-s'
    ,type=str
    ,required=True
    ,help='软件的根目录路径'
)
parser.add_argument(
    '-r'
    ,type=str
    ,required=True
    ,help='mmd文件所在的目录路径'
)
args = parser.parse_args()

software_root = args.s
root_dir = args.r

for root, dirs, files in os.walk(root_dir):
    prefix=''
    if root != root_dir:
        prefix=root[len(root_dir)+1:]
    for file in files:
        if file.endswith(".mmd"):
            rfile = os.path.join(prefix,file)
            path = os.path.join(root,file)
            with open(path,'r') as f:
                # print(path)
                lines = f.readlines()
                # print(lines)
                deps=[]
                for line in lines:
                    tokens=line.split()
                    # tokens.extend(line.split())
                    for token  in tokens:
                        if token[-1]=="\\" or token.endswith(':'):
                            continue
                        deps.append(token)
                # for d in deps:
                #     print(d)
                # exit(1)
                if prefix=='':
                    prefix_dirs=[]
                else:
                    prefix_dirs = prefix.split('/')
                # print(dirs)
                # print(prefix_dirs,prefix)

                for d in deps[1:]:
                    # if os.path.exists(os.path.join(software_root,d)):
                    #     # print(d)
                    #     pass
                    if d[0]!='/':
                        s = []
                        for e in prefix_dirs:
                            s.append(e)
                        # if s[0] == '':
                        #     print(s)
                        d_dirs = d.split('/')
                        for i in d_dirs:
                            if i == '..':
                                s.pop()
                                continue
                            s.append(i)
                        rd='/'.join(s)
                        if not os.path.exists(os.path.join(software_root,rd)):
                            # print(os.path.join(software_root,rd))
                            if os.path.exists(os.path.join(software_root,d)):
                                rd=d
                            else:
                                continue
                        d=rd
                        # print(d)
                    print('depends',rfile[:-4],d)
                    # if d[0]=='/':
                    #     print(d)

